package stark.app.function.filetransfer;

import android.content.Intent;
import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.apkextract.lib.model.AeUtil;
import com.stark.file.transfer.FileSendShowQrActivity1;
import com.stark.file.transfer.core.FileInfo;
import com.stark.file.transfer.core.Transferable;
import com.stark.file.transfer.core.TransferableSendManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.app.R;
import stark.app.databinding.FragmentSendApkBinding;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.constant.FileType;
import stark.common.basic.utils.RxUtil;

/**
 * Author：daizhongbin on 2023/10/25
 * Email：1027154338@qq.com
 * Desc:
 */
public class SendApkFragment extends BaseNoModelFragment<FragmentSendApkBinding> {

    private ApkAdapter mApkAdapter;
    private List<ApkBean> mSelApkBeans = new ArrayList<>();

    @Override
    protected int onCreate() {
        return R.layout.fragment_send_apk;
    }

    @Override
    protected void initView() {
        mDataBinding.rvApk.setLayoutManager(new LinearLayoutManager(getContext()));
        mDataBinding.rvApk.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.set(0, 0, 0, SizeUtils.dp2px(1));
            }
        });
        ApkAdapter apkAdapter = new ApkAdapter();
        apkAdapter.setOnItemClickListener(this);
        mApkAdapter = apkAdapter;
        mDataBinding.rvApk.setAdapter(apkAdapter);

        mDataBinding.tvSend.setOnClickListener(v -> {
            handleClickSend();
        });
    }

    @Override
    protected void initData() {
        loadApks();
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        ApkBean apkBean = mApkAdapter.getItem(position);
        apkBean.setSelected(!apkBean.isSelected());
        mApkAdapter.notifyItemChanged(position);
        addOrDelApkBean(apkBean);
    }

    private void loadApks() {
        showDialog(getString(com.stark.common.res.R.string.loading));
        RxUtil.create(new RxUtil.Callback<List<String>>() {
            @Override
            public void doBackground(ObservableEmitter<List<String>> emitter) {
                emitter.onNext(AeUtil.getNoSystemInstalledPackageNames());
            }

            @Override
            public void accept(List<String> packageNames) {
                dismissDialog();
                if (packageNames != null && packageNames.size() > 0) {
                    List<ApkBean> apkBeans = new ArrayList<>();
                    ApkBean bean;
                    for (String packageName : packageNames) {
                        bean = new ApkBean();
                        bean.pkgName = packageName;
                        apkBeans.add(bean);
                    }
                    mApkAdapter.setNewInstance(apkBeans);
                }
            }
        });
    }

    private void addOrDelApkBean(ApkBean apkBean) {
        if (apkBean.isSelected()) {
            if (!mSelApkBeans.contains(apkBean)) {
                mSelApkBeans.add(apkBean);
            }
        } else {
            mSelApkBeans.remove(apkBean);
        }
        mDataBinding.tvSend.setVisibility(mSelApkBeans.size() > 0 ? View.VISIBLE : View.GONE);
    }

    private void handleClickSend() {
        List<Transferable> fileInfoList = convert(mSelApkBeans);
        TransferableSendManager.getInstance().setTransferables(fileInfoList);
        startActivity(new Intent(getActivity(), FileSendShowQrActivity1.class));
    }

    private static List<Transferable> convert(List<ApkBean> apkBeans) {
        List<Transferable> transferableList = new ArrayList<>();
        FileInfo fileInfo = null;
        AppUtils.AppInfo appInfo;
        for (ApkBean bean : apkBeans) {
            appInfo = AppUtils.getAppInfo(bean.pkgName);
            fileInfo = new FileInfo();
            fileInfo.setFileName(appInfo.getName() + ".apk");
            fileInfo.setFileType(FileType.APK);
            File apkFile = new File(appInfo.getPackagePath());
            fileInfo.setUriStr(AeUtil.file2Uri(apkFile).toString());
            fileInfo.setSize(apkFile.length());
            transferableList.add(fileInfo);
        }
        return transferableList;
    }
}
